package com.tencreat.common.utils;

import com.alibaba.fastjson.JSONObject;
import com.tencreat.common.exception.CustomException;
import com.tencreat.common.utils.http.HttpUtils;
import org.apache.tomcat.util.codec.binary.Base64;

import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 描述信息
 *
 * @Author lx
 * @Company: 深圳腾创互联科技有限公司
 * @link: https://tencreat.com
 * @Date: 2022/6/30 0030 14:43
 */
public class LianSignUtils {
    public static void main(String[] args) {
        Map<String, Object> jsonObject = new HashMap<>();
        // JSONObject jsonObject = new JSONObject();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        jsonObject.put("api_version", 1.0);
        //Map<String,Object> map = new HashMap<>();
        jsonObject.put("sign_type", "RSA");
        // 时间
        jsonObject.put("time_stamp", sdf.format(new Date()));
        // 商户号
        jsonObject.put("oid_partner", "201408071000001539");
        // 用户id
        jsonObject.put("user_id", "256989");
        // 虚拟还是实物   109001
        jsonObject.put("busi_partner", "101001");
        // 订单号
        jsonObject.put("no_order", "16588855666666");
        // 下单时间
        jsonObject.put("dt_order", sdf.format(new Date()));
        // 商品名称
        jsonObject.put("name_goods", "购买藏品");
        // 交易金额
        jsonObject.put("money_order", "0.01");
        // 回调地址
        jsonObject.put("notify_url", " http://49ftxk.natappfree.cc");
        // 风控参数
        JSONObject jsonObject1 = new JSONObject();
        // 商品类目
        jsonObject1.put("frms_ware_category", "4007");
        // 用户id
        jsonObject1.put("user_info_mercht_userno", "256989");
        // 手机号码
        jsonObject1.put("user_info_bind_phone", "13487821230");
        // 注册时间
        jsonObject1.put("user_info_dt_register", sdf.format(new Date()));
        // 商品名称
        jsonObject1.put("goods_name", "购买藏品");
        // 真实姓名
        jsonObject1.put("user_info_full_name", "龙弦11");
        // 户口类型
        jsonObject1.put("user_info_id_type", 0);
        // 身份证号码
        jsonObject1.put("user_info_id_no", "430903199901054522");
        // 商户是否对用户有实名认证 1-是 0-否
        jsonObject1.put("user_info_identify_state", 1);
        // 实名认证方式。
        //1 - 银行卡认证。
        //2 - 现场认证。
        //3 - 身份证远程认证。
        //4 - 其他认证。
        jsonObject1.put("user_info_identify_type", 4);
        // 风控数据
        jsonObject.put("risk_item", jsonObject1.toJSONString());
        // 支付产品标识。
        //0， 快捷收款。
        //1， 认证收款。
        //2， 网银收款。
        //5， 新认证收款。
        //12， 手机网银收款 。
        jsonObject.put("flag_pay_product", 0);
        // 应用渠道标识。
        //0， App-Android。
        //1， App-iOS。
        //2， Web。
        //3， H5。
        jsonObject.put("flag_chnl", 3);

        String private_key = "MIIJQwIBADANBgkqhkiG9w0BAQEFAASCCS0wggkpAgEAAoICAQCtH+GJtV33S5RF" +
                "SDxnD2VhRLcB+2GXq9qLzgzDBrNNrXyjiMdUDRU2tFrNBIjq43BSIPCacLRriV5X" +
                "7o1i6HkP6bPEsLEIaRCNzvPZ1cz9amSGKMpfaEwRnFK4qDDONj5FktcdY34iVmaG" +
                "1jvfxOrvEGcW4qPnv2/ZK+UK38y72F/qvem3xVXB0YN7f2wkP6WkdctytrGFjrym" +
                "EsklSuWR8x9j+nny918EwjcdYzy/652Pt4vK+R1wv19e0D6nZCzcMoJuFJB8Obr6" +
                "3Jg48wqpQ1m0jL9M3cc52YbanOReOpuq4REFdAjDrQQVONQ4x9H7jo6hOpV8J/TC" +
                "yL95RUPzVhRXIH1qKRu4Nb14b2r32pFlLMMqfouW0jLXOExio878cpuYnnVV7tYR" +
                "EIvS1nlBzmAV89CeqRgtc6Kx1FpfgvXg7JxejlRtuOBbz2F4fe8xyiKtoqSd/qWU" +
                "FuGttm/FH6IeHvXguaQxo6HG81YXEtESXIcc37SNYn+qperYWXYGLLiRd3WxJflJ" +
                "bdfIbnT7ZMPJx+GsujAnYsnf4zFOT/jSxbdHLKJHjf1fMX+/t/zNeWDt3dgDP69C" +
                "F4NqHaJosxQWRmpivX+TnbSaSqAYoDnYgHqP3OMsOw9XFXjh2m5J2j7WonCD1W8o" +
                "Ziy8YDPsGJSy9r0Z2M9hhc982cq1xQIDAQABAoICABi14XkIpmAfDUuDRz3VlHyY" +
                "9H8nrJMbwC6uyyMGII8giVcFNaBBWssLXJ+BO3K9YmGSmo0Ms6/atFjcL5mTwX3c" +
                "N2DGcIpZBrga9zLbQa5VIoKErXgHOL5Vv/fj581zMBm5nxMuiYkoqGssBnFG19qm" +
                "DnTVhhwUtsf6bC+MaJpSRMSKdWLZ24b12uzEcADPhdrOxmp5+aYszK/uo/+67EAU" +
                "AeHBFWlw1gLlnrzG1pu1K3DhO6aNvp5CboAnvJ2jXoTSf8vrCwF0MwRN+rs8M4Qb" +
                "3SC4azCzQhW3fvhSpwTtHB18kPOkj4CwgBHwYdg16zqa6zBHnqERSe4Ifc33LT7A" +
                "vaJkgFf1FhEYaOYC4rWdmpfyCf0/mRiyrQ1ztRioEMwT+Ftv2vw06K+UF151j8Hy" +
                "YBzcSbYrJ4yEzIQTl45IYLtzIxw6sSjmkfM8dOvchjqBTioWzcmqHOYE4GReDHmb" +
                "kBSH89r7oNEWJkpW3tiHhWMGOMWeLRUVEDBSPgOqpOyUFu0m40NX624yeJQdqAyJ" +
                "4ffstskg3L6q7KNiQhrf0Aumf6fknx6dwTd+5/d5eS78MNaDRCYqTV4Qg/8Wp4QO" +
                "nLsR9qwPy1540Cf/wGfrNQzYktFFMea/H8QZrzx5bzRb3NXQFQIIT/PjfBYtg/qY" +
                "aPgSk6jYa2R9Z+JRbgPBAoIBAQDCv97zJMyhoG9cCwJg8cp31kOt5XtRMmM9oQ3Q" +
                "/a9yqKkSKQl0vmKqIkMHVzg7xSgybqUBS2Gs5p/IvZOpoeSkYgXObxVMKCrhAy46" +
                "Lx3YdT5QWD0etmg3Mtbd54YWhEECOWwqdPsIPVfL2L6WVdCRptcM3ebNeosrGFap" +
                "BJe8ix12ixWWZhzTUhUYcC9LjB/KCQMk3xIH90QTfBXWtzXDN5FvvUHKQf1joR2r" +
                "Gi6rHvJrGI9HOxJ2yho1oZXjSY8LP9GTmQ7TeiAA4cTQ3idtZWY5ocyfH3m8AkTw" +
                "as9tuvnxxqFJ/UDFQbQ8grLodoe0vg1RQF1XgoJwPMPNDm3BAoIBAQDjkuP1lDVp" +
                "mIyCelcHKsbmhN+6fL3dNu36Xma3jb5/QA+GqukyAlFk4CBc2toHoEPxUEhijZmg" +
                "fKFzjrdN3QaGunLN67tKHMhLE8mwJix+NzHaAmUMohwHfF5qOFjVJZCGXvFnt0HW" +
                "w3Zwbe8slxeYChgurqQjBkxLqWHPa2kCbxRxsObQm89EU2OZeuBDpKWAUexySm1U" +
                "t/sGlKs3LU5/74ABcA1TrfjR3br4eKUT782KMVWaKNZA6AvzUDuB/BxMU2Xa/jWZ" +
                "WDWusNzThJSF7Kv6KMSp/YacuwEKpKmmvA/HKIfcKPTvRNOkVOngVUb8p8Y4EtIG" +
                "+dP4ywga6NEFAoIBAQCmmwKeu8KcGuZptblpOjDd6F2p7QJcamDgHmH1grGPw54w" +
                "PQ8r4pwBtKHnK8SdzYMf8ewTeWusQPg9AYHLwwYZYwpYmkt8BXj5WoE3oYtE3Lhc" +
                "f8B5/86UOlf7KtBZfvcmcf2JLN59JA1yBJC3h96QXEzpYwTKkKVyTrYEjjtJPzIL" +
                "cd0b92t9lWEasQ6k8NFZQ/B+oJ+KVQzWJneAYugJhAZVs3EPGPkvPGxnLlTya90z" +
                "paUdaPnYyfk2HHBgK1PGaehe/rfiTz4Fwx9fGE5eljqn3zVwg7rfDonvq1CdLTIa" +
                "lrTw2UmJ9zW79owbtxtNkrFN62RvMuVoI3PWfxuBAoIBAQCqdJvKlfhr35dfI8OL" +
                "2r6ga2YoiMatqzcVESBe3AyTw6fddqa0jofoxvd2lXY5wBEj7r5JE0a+rps/suYZ" +
                "rDP3NjBHjQn7uRNNKMUo627oGu98G88UZ1gXQ1B0vz/KZxiZjQPEa78k3cMY8z7y" +
                "ZzmE6Aq07JqEoXMEORrKAenlqM3nWlmIZywYQV2Y2DCiefB87N/tu1Go4yVjCHg2" +
                "G/lwWjPG3+cbhnOYvjwNYFBFXpjVqZ40meHhO+23kaEA+5U2lkD0hvQep7ON5WuC" +
                "Aww8Q8mM1nx31y28t1VQY4WvHa2zvugEP6k2jpb3v6JuJXHGTORrm601DGt5Lpoj" +
                "jb8BAoIBAE3RgfNdJ7yXb6/WxINYU7We9wX/tftpK+SHESJ6Yt3E8OEf+y5IpNWm" +
                "LXUPj5kfMeXut0ZLxmV0d5Q6CCZa6LBqntmDYZYQFMPahz7bWLbxOoCOqnZ8TAA1" +
                "/H4Jn2lwXT+DhCHFi3wAx6cPDguY41jzDzgrXLQ84lbk8MIpNpTyaAFecVtaDKyc" +
                "4r67ZlwCAcLvZblvwmkicKcf9fJE/tUIa7O2aT6+9oJ2c6R7uESXh06t6/5KNwFq" +
                "4hRg5j4YCmwe9ObFERZoe8MDAgncAxHcSSsjmy/a8i9xDp+LkTRxnztnhOwCvUKZ" +
                "Zt7fY3PzqzjpZffLFGwZXjaz0DntY0o=";

        private_key = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAKZGXpmfgya2gGh6UdFPqPqi6e2z/HX4aIlMH394FOXTVwErnSGY5S0YFw5WskJrQLU2RHwFiA5P9Yt8VPxwgLDpdIm1/a7NlyjvWNvBd8V7wyITH8teJA1Ae5yWmRRrWFcVRSjpBq3xfwv76lVl+Nq/jR08p/ugVYJgtYEIM53JAgMBAAECgYA17SarPj+j45a7y8gTUXmlaAbkb/ZWMG1+8fBZQBHPA/74wzNf/R1+xYxcuyNvRSekXehSLN0WfzpMtdM+WCJ0ODqHRFsbAxmi784hzBZHOAxoJV49P8PVy6HIPthXxiSNUcacSt/HKJrUI6zACpymJLiVxMb9GqQAyx3BJl7rjQJBANG+RDszZYl3J1z1AtD0WggycrH2YOB7v5o3qKOz2AQ6CHWApSN6cuvqFwaUtHK9gMpDhvWR6zbYVRP+f4AxoQ8CQQDK8fTkpHNrHc011E8jjk3Uq5PWTJ0jAvcqk4rqZa4eV9953YSJYtJ2Fk2JnL3Ba7AU+qStnyD6MvSIpwIPSaOnAkEAptbFaZ4Jn55jdmMC2Xn1f925NGx6RTbKg37Qq18sbrhG8Ejjk2QctCIiLL7vBvJM1xd97CslQhw1GNFxVGSl6wJAQzwFtfoFgudMpRjBXzY18s8lG0omhQLmf+SBkUY+eS8Diowo7Jsgvp6E8aJL+1iB7XFcPWkKs9lNyjgKJqZu4QJAM22ULfWKrNIqaBJaYDmQSupUkHR/WL5rQJtAuVo8Zg3+rBrtMTXfIHJpR0MNpMgRSsPK6pZ3n4i+VvC5WxKUzA==";
        Map<String, Object> sortMap = new TreeMap<String, Object>(new Comparator<String>() {

            @Override
            public int compare(String o1, String o2) {

                return ((String) o1).compareTo((String) o2);
            }
        });

        sortMap.putAll(jsonObject);
        String s1 = sortMap.toString().replaceAll(", ", "&");
//        s1 = s1.replace("{", "");
//        s1 = s1.replace("}", "");
        s1 = s1.substring(1, s1.length()-1);
        String sign = null;
        try {
            sign = sign(s1, private_key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (sign == null) {
            throw new CustomException("生成签名异常");
        }
        jsonObject.put("sign", sign);
        JSONObject json = new JSONObject(jsonObject);
        String s = HttpUtils.sendPostV2("https://payserverapi.lianlianpay.com/v1/paycreatebill", json.toJSONString());
        System.out.println("返回数据-----------" + s);


    }

    /**
     * 签名
     *
     * @param data       待签名数据
     * @param privateKey 私钥
     * @return 签名
     */
    public static String sign(String data, PrivateKey privateKey) throws Exception {
        byte[] keyBytes = privateKey.getEncoded();
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey key = keyFactory.generatePrivate(keySpec);
        Signature signature = Signature.getInstance("MD5withRSA");
        signature.initSign(key);
        signature.update(data.getBytes());
        return new String(Base64.encodeBase64(signature.sign()));
    }

    /**
     * rsa签名
     *
     * @param content    待签名的字符串
     * @param privateKey rsa私钥字符串
     * @param charset    字符编码
     * @return 签名结果
     * @throws Exception 签名失败则抛出异常
     */
    public static String sign(String content, String privateKey) throws Exception {

        //base64编码的私钥
        try {
            //RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));

            // 取得私钥
            byte[] pri_key_bytes = Base64.decodeBase64(privateKey);
            PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(pri_key_bytes);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            // 生成私钥
            PrivateKey priKey = keyFactory.generatePrivate(pkcs8KeySpec);

            return sign(content, priKey);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    /**
     * 验签
     *
     * @param srcData 原始字符串
     * @param publicKey 公钥
     * @param sign 签名
     * @return 是否验签通过
     */
    public static boolean verify(String srcData, PublicKey publicKey, String sign) throws Exception {
        byte[] keyBytes = publicKey.getEncoded();
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey key = keyFactory.generatePublic(keySpec);
        Signature signature = Signature.getInstance("MD5withRSA");
        signature.initVerify(key);
        signature.update(srcData.getBytes());
        return signature.verify(Base64.decodeBase64(sign.getBytes()));
    }

    /**
     * 验签
     *
     * @param srcData 原始字符串
     * @param publicKey 公钥
     * @param sign 签名
     * @return 是否验签通过
     */
    public static boolean verify(String srcData, String publicKey, String sign) throws Exception {
        byte[] publicBytes = Base64.decodeBase64(publicKey);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey pubKey = keyFactory.generatePublic(keySpec);
        return verify(srcData,pubKey,sign);
    }
}
